/*
	Copyright (c) 2010 <copyright holders>
	This source code is licensed under The MIT License,
	see the file LICENSE for details.
	*/

#include "SmoothFloat.hpp"

#include <algorithm>
#include <cmath>

namespace spelprog2 {

SmoothFloat::SmoothFloat(float value, float speed):
    speed(speed),
    current(value),
    target(value)
{}

void SmoothFloat::update(float time)
{
    if(delta > 0.0f)
        current = std::min(target, current + delta*time);
    else
        current = std::max(target, current + delta*time);
}

void SmoothFloat::set(float value, float speed)
{
    this->speed = speed;
    target = value;
    delta = (target - current)/speed;
}

void SmoothFloat::setPeriodical(float value, float period, float speed)
{
    this->speed = speed;
    
    current = fmod(period*((int)fabs(current/period) + 1) + current, period);
    value = fmod(period*((int)fabs(value/period) + 1) + value, period);
    
    if(value > current)
    {
        if(fabs(value-current) > fabs(current + period - value))
        {
            value = value - period;
        }
    }
    else
    {
        if(fabs(value-current) > fabs(value + period - current))
        {
            current = current - period;
        }
    }
    
    set(value);
}

void SmoothFloat::setImmediate(float value)
{
    target = value;
    current = value;
}

float SmoothFloat::get()
{
    return current;
}

float SmoothFloat::getDelta()
{
    return delta;
}

}; //namespace spelprog2